package com.olc.railing.busniess;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.olc.railing.base.BaseApplication;
import com.olc.railing.constant.Constants;
import com.olc.railing.constant.Urls;
import com.olc.railing.http.GasCallBack;
import com.olc.railing.http.HttpBusiness;
import com.olc.railing.http.LocalCommonBackJson;
import com.olc.railing.http.WrapperNetBusiness;
import com.olc.railing.model.BillInfo;
import com.olc.railing.model.ConfigInfo;
import com.olc.railing.model.GasOrderInfo;
import com.olc.railing.orm.BillInfoDao;
import com.olc.railing.services.UploadTradeInfoServices;
import com.olc.railing.utils.CommUtils;
import com.olc.railing.utils.MyLog;
import com.olc.railing.utils.SharedUtils;
import com.olc.railing.utils.ShellUtils;
import com.tyxh.paylibrary.exception.BaseException;
import com.tyxh.paylibrary.exception.NetNotAvailableException;
import com.tyxh.paylibrary.exception.NullException;
import com.tyxh.paylibrary.listener.EtcCallBack;
import com.tyxh.paylibrary.listener.ResultCallBack;
import com.tyxh.paylibrary.model.GasPayBusiness;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;


public class DataBusiness {

    private static DataBusiness dataBusiness;
    private static Context context;
    private static Gson gson = new Gson();
    public final static int UPLOAD_INTERVAL_TIME = 20 * 1000;
    public final static int ERROR_CODE = -1;
    public final static int CONNECT_FAIL = 110;
    public final static int NOTICE_GAS_SUCCESS = 100;
    public final static int NOTICE_GAS_FAIL = 101;
    public final static int PATCH_ORDER_FAIL = 102;
    public final static int PATCH_ORDER_SUCCESS = 103;
    public final static int ETC_PAY_SUCCESS = 104;
    public final static int ETC_PAY_FAIL = 105;

    public final static int TRADE_UPLOAD_SUCCESS = 106;
    public final static int TRADE_UPLOAD_FAIL = 107;
    public final static int NO_OIL_GUN_NO = 108;

    public final static int QUERY_CONFIG_FAIL = 110;
    public final static int QUERY_CONFIG_SUCCESS = 111;

    public final static int INSTALL_SUCCESS = 112;

    public final static int HEART_BEAT_SUCEESS_CODE = 119;
    public final static int DOWN_FILE_SUCEESS_CODE = 120;
    public final static int N0_RECOGINISE_VEHPLATE = 121;


    private boolean isDownloadApk = true;
    private static final String TAG = DataBusiness.class.getSimpleName();


    private DataBusiness(Context context) {
        this.context = context;
    }

    public static DataBusiness getInstance(Context context) {
        if (dataBusiness == null) {
            dataBusiness = new DataBusiness(context);
        }
        return dataBusiness;
    }
    /**
     * 获取未支付订单并且完成支付
     */
    public void fetchOrderAndPay(String plateNo,final Handler handler) {
      // String time =  NTPClient.getInstance().getNTPServerTime();
     //   MyLog.d(MyLog.TAG,"fetchOrderAndPay "+time);
        MyLog.e(MyLog.TAG,"fetchOrderAndPay "+plateNo + " "+SharedUtils.getOilGunNo(context) );
        try {
            if(TextUtils.isEmpty(plateNo)){
                handler.sendEmptyMessage(N0_RECOGINISE_VEHPLATE);
                return;
            }
            if(TextUtils.isEmpty(SharedUtils.getOilGunNo(context))){
                handler.sendEmptyMessage(NO_OIL_GUN_NO);
                return;
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("action","P001");
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("plateNumber",plateNo);
            jsonObject1.put("gunNumber",SharedUtils.getOilGunNo(context));
            jsonObject.put("data",jsonObject1);
            WrapperNetBusiness.fetchNoPayOrder(context, jsonObject.toString(), new GasCallBack<GasOrderInfo>() {
                @Override
                public void onResponse(GasOrderInfo gasOrderInfo) {
                    if(gasOrderInfo!=null){
                        if(TextUtils.isEmpty(gasOrderInfo.getGoodsName())){
                            gasOrderInfo.setGoodsName(gasOrderInfo.getGoodsCode()+"#");
                        }
                        setGasOrderInfo(gasOrderInfo);
                        handler.sendEmptyMessage(PATCH_ORDER_SUCCESS);
                    }

                }

                @Override
                public void onError(String error) {
                    Message message =  handler.obtainMessage();
                    message.obj  = error;
                    message.what = PATCH_ORDER_FAIL;
                    handler.sendMessage(message);

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void etcPay(String plateNo, Handler businessHandler){

        try {
            GasPayBusiness.getInstance().etcPay(plateNo,mGasOrderInfo.getTotalMoney(),
                    mGasOrderInfo.getTotalMoney() - mGasOrderInfo.getPayMoney(),"",
                    mGasOrderInfo.getGoodsName(),mGasOrderInfo.getLitter(),
                    mGasOrderInfo.getUnitPrice(), true, CommUtils.getPaySerialNo(),
                    "", new EtcCallBack() {
                        @Override
                        public void onFail(BaseException exception) {
                            Message message =  businessHandler.obtainMessage();
                            message.obj  = exception;
                            message.what = ETC_PAY_FAIL;
                            businessHandler.sendMessage(message);


                        }

                        @Override
                        public void onResponse(int code, String message, String data) {

                            businessHandler.sendEmptyMessage(ETC_PAY_SUCCESS);

                        }

                    });
        } catch (NullException exception) {

            Message message =  businessHandler.obtainMessage();
            message.obj  = exception;
            message.what = ETC_PAY_FAIL;
            businessHandler.sendMessage(message);

        }
    }
    /**
     * 支付成功
     * @param data
     * @param gasOrderInfo
     */
    public static int notifyTimes;
    public void notifyGasStation(Handler handler, String billUuid) {
        MyLog.d(MyLog.TAG,"notifyGasStation start");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("action","P002");
            jsonObject.put("data",new Gson().toJson(mGasOrderInfo));
            WrapperNetBusiness.synPayedOrder(context,jsonObject.toString() , new GasCallBack<String>() {
                @Override
                public void onResponse(String invoiceUrl) {
                    Message message = handler.obtainMessage();
                    message.obj = billUuid +"|"+invoiceUrl;
                    message.what = NOTICE_GAS_SUCCESS;
                    handler.sendMessage(message);

                }

                @Override
                public void onError(String error) {
                    Message message = handler.obtainMessage();
                    notifyTimes++;
                    message.arg1 = notifyTimes;
                    message.what = NOTICE_GAS_FAIL;
                    String data =  billUuid +"|"+error;
                    MyLog.e(MyLog.TAG,"notifyGasStation onError "+data +" notifyTimes: "+notifyTimes);
                    message.obj = data;
                    handler.sendMessage(message);

                }
            });
        } catch (NullException e) {
            MyLog.e(MyLog.TAG,"notifyGasStation "+e.toString());
        } catch (NetNotAvailableException e) {
            MyLog.e(MyLog.TAG,"notifyGasStation "+e.toString());
        } catch (JSONException e) {
            MyLog.e(MyLog.TAG,"notifyGasStation "+e.toString());
        }
    }

    private  GasOrderInfo mGasOrderInfo;
    public void setGasOrderInfo(GasOrderInfo gasOrderInfo) {
        this.mGasOrderInfo = gasOrderInfo;
    }

    public  GasOrderInfo getmGasOrderInfo() {
        return mGasOrderInfo;
    }

    public void uploadTradeInfo(Context context, BillInfo billInfo, Handler handler){
        try {
            String var = billInfo.getGasInfoData();
            String var1 = billInfo.getBillInfoData();
           // MyLog.e(MyLog.TAG,"uploadTradeInfo var "+var);
            JSONObject  jsonObject1 = new JSONObject(var);
            JSONObject jsonObject2 = new JSONObject(var1);

            GasPayBusiness.getInstance().uploadTreadInfo(context, jsonObject1, new EtcCallBack() {
                @Override
                public void onFail(BaseException e) {
                    Message message = handler.obtainMessage();
                    message.obj = billInfo.getBillUuid();
                    message.what = TRADE_UPLOAD_FAIL;
                    handler.sendMessage(message);
                }

                @Override
                public void onResponse(int i, String s, String s1) {
                    uploadBill(context, jsonObject2,handler,billInfo.getBillUuid());

                }
            });
        } catch (NullException e) {
            e.printStackTrace();
        } catch (NetNotAvailableException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public void uploadBill(Context context, JSONObject jsonObject, Handler handler, String uuid){
        try {
            GasPayBusiness.getInstance().uploadBill(context, jsonObject, new EtcCallBack() {
                @Override
                public void onFail(BaseException e) {
                    MyLog.d(MyLog.TAG,"uploadBill onFail ");
                    Message message = handler.obtainMessage();
                    message.obj = uuid;
                    message.what = TRADE_UPLOAD_FAIL;
                    handler.sendMessage(message);
                }

                @Override
                public void onResponse(int i, String s, String s1) {
                    MyLog.d(MyLog.TAG,"uploadBill onResponse ");
                    Message message = handler.obtainMessage();
                    message.obj = uuid;
                    message.what = TRADE_UPLOAD_SUCCESS;
                    handler.sendMessage(message);
                }
            });
        } catch (NullException e) {
            e.printStackTrace();
        } catch (NetNotAvailableException e) {
            e.printStackTrace();
        }
    }




    public void queryConfig( Handler handler)  {
        MyLog.d(MyLog.TAG,"queryConfig");
        TreeMap<String,String> data = new TreeMap<>();
        data.put("dev_number",CommUtils.getDeviceSN());//dbee29f4c239cf06  dbee29f4c239cf06
        try {
            HttpBusiness.getInstance().get(context, Urls.QUERY_CONFIG, data, new ResultCallBack<LocalCommonBackJson>() {
                @Override
                public void onFail(int i, Exception e) {
                    handler.removeMessages(QUERY_CONFIG_FAIL);
                    Message message = handler.obtainMessage();
                    message.what = QUERY_CONFIG_FAIL;
                    handler.sendMessage(message);
                }

                @Override
                public void onResponse(int i, LocalCommonBackJson localCommonBackJson) {
                    ConfigInfo configInfo = new Gson().fromJson(localCommonBackJson.getData(),ConfigInfo.class);
                    fetchUkey(handler,configInfo);
                }


                @Override
                public void onHttpFail(int i, String s) {
                    handler.removeMessages(QUERY_CONFIG_FAIL);
                    Message message = handler.obtainMessage();
                    message.what = QUERY_CONFIG_FAIL;
                    handler.sendMessage(message);
                }
            });
        } catch (NetNotAvailableException e) {
            e.printStackTrace();
        } catch (NullException e) {
            e.printStackTrace();
        }


    }

    /**
     * push_time	是	string	挡车杆系统时间
     * dev_number	是	string	设备编号
     * dev_type	否	string	设备类型
     * status_info
     */

    public void pushHeart(  )  {
        TreeMap<String,String> data = new TreeMap<>();
        data.put("push_time",(System.currentTimeMillis()/1000)+"");
        data.put("dev_number",CommUtils.getDeviceSN());
        data.put("dev_type", Constants.DEV_TYPE);
        data.put("status_info",CommUtils.getVerName(BaseApplication.getApplication()));
        try {
            HttpBusiness.getInstance().post(context, Urls.PUSH_HEART, data, new ResultCallBack<LocalCommonBackJson>() {
                @Override
                public void onFail(int i, Exception e) {

                }

                @Override
                public void onResponse(int i, LocalCommonBackJson localCommonBackJson) {

                    try {
                        if("0".equals(localCommonBackJson.getErr_code())){
                            String data = localCommonBackJson.getData();
                            if(!TextUtils.isEmpty(data)){
                                JSONObject jsonObject = new JSONObject(data);
                                int is_need_get_log = jsonObject.getInt("is_need_get_log");
                                String log_date = jsonObject.getString("log_date");

                                int is_new_version = jsonObject.getInt("is_new_version");
                                String file_name = jsonObject.getString("file_name");
                                String upload_time = jsonObject.getString("upload_time");
                                String version = jsonObject.getString("version");
                                //MyLog.d(MyLog.TAG,"is_need_get_log: "+is_need_get_log);
                                if(is_need_get_log == 1){
                                    pushLog(log_date);
                                }
                                if(is_new_version == 1&&isDownloadApk){
                                    isDownloadApk = false;
                                    downloadApk(file_name,upload_time,version);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                   // {"is_new_version": 1, "is_need_get_log": 0, log_date
                    // "file_name": "update_install_v123.apk",
                    // "version": "v123", "upload_time": 1631672069}
                }


                @Override
                public void onHttpFail(int i, String s) {

                }
            });
        } catch (NetNotAvailableException e) {
            e.printStackTrace();
        } catch (NullException e) {
            e.printStackTrace();
        }


    }


    public void fetchUkey(Handler handler, ConfigInfo configInfo )  {
        TreeMap<String,String> data = new TreeMap<>();
        data.put("gas_id",configInfo.getGas_id());
        data.put("dev_number",CommUtils.getDeviceSN());
        data.put("dev_type", Constants.DEV_TYPE);
        try {
            HttpBusiness.getInstance().post(context, Urls.FETCH_U_KEY, data, new ResultCallBack<LocalCommonBackJson>() {
                @Override
                public void onFail(int i, Exception e) {
                    handler.removeMessages(QUERY_CONFIG_FAIL);
                    Message message = handler.obtainMessage();
                    message.what = QUERY_CONFIG_FAIL;
                    handler.sendMessage(message);
                }

                @Override
                public void onResponse(int i, LocalCommonBackJson localCommonBackJson) {
                    String data = localCommonBackJson.getData();
                    if(!TextUtils.isEmpty(data)){
                        configInfo.setAppKey(data);
                        handler.removeMessages(QUERY_CONFIG_SUCCESS);
                        Message message = handler.obtainMessage();
                        message.obj = configInfo;
                        message.what = QUERY_CONFIG_SUCCESS;
                        handler.sendMessage(message);
                    }
                }


                @Override
                public void onHttpFail(int i, String s) {
                    handler.removeMessages(QUERY_CONFIG_FAIL);
                    Message message = handler.obtainMessage();
                    message.what = QUERY_CONFIG_FAIL;
                    handler.sendMessage(message);
                }
            });
        } catch (NetNotAvailableException e) {
            e.printStackTrace();
        } catch (NullException e) {
            e.printStackTrace();
        }


    }

    /**
     * dev_number	是	string	设备编号
     * file_name	是	string	文件名称
     * remark
     */
    public void pushLog(String needDate)  {
        String fileName = getFileName(needDate);
        MyLog.d(MyLog.TAG,"pushLog fileName : "+fileName);
        TreeMap<String,String> data = new TreeMap<>();
        data.put("file_name",fileName);
        data.put("dev_number",CommUtils.getDeviceSN());
        data.put("remark","");
        try {
            HttpBusiness.getInstance().uploadFile(context, Urls.PUSH_LOG, data,Constants.FILE_PATH_INFO.get(Constants.FILE_PATH_DIR_LOG),fileName, new ResultCallBack<LocalCommonBackJson>() {
                @Override
                public void onFail(int i, Exception e) {

                }

                @Override
                public void onResponse(int i, LocalCommonBackJson localCommonBackJson) {

                }


                @Override
                public void onHttpFail(int i, String s) {

                }
            });
        } catch (NetNotAvailableException e) {
            e.printStackTrace();
        } catch (NullException e) {
            e.printStackTrace();
        }


    }

    /**
     * dev_number	是	string	设备编号
     * file_name	是	string	安装包名称【心跳中含带】 格式;update_install_v112.apk【其中’v’后面三位数字为版本号】
     * upload_time
     * @param fileName
     * @param version
     */
    public void downloadApk(String fileName, String uploadTime, String version)  {
        MyLog.d(MyLog.TAG,"downloadApk fileName : "+fileName);
        TreeMap<String,String> data = new TreeMap<>();
        data.put("file_name",fileName);
        data.put("dev_number",CommUtils.getDeviceSN());
        data.put("upload_time",uploadTime);
        try {
            HttpBusiness.getInstance().downloadFile(context, Urls.DOWNLOAD_APK, data,"dcg.apk", new ResultCallBack<LocalCommonBackJson>() {
                @Override
                public void onFail(int i, Exception e) {
                    isDownloadApk = true;
                }

                @Override
                public void onResponse(int i, LocalCommonBackJson localCommonBackJson) {
                  //  MyLog.d(MyLog.TAG,localCommonBackJson.getData());
                    if("100".equals(localCommonBackJson.getErr_msg())){
                        File file = new File(localCommonBackJson.getData());
                        MyLog.d(MyLog.TAG,"下载成功 path: "+localCommonBackJson.getData()+" size: "+file.length()+" version :"+version);
                        updateStatus(version, 0,localCommonBackJson.getData(),false);
                    }else{
                        isDownloadApk = true;
                    }
                }


                @Override
                public void onHttpFail(int i, String s) {
                    isDownloadApk = true;
                }
            });
        } catch (NetNotAvailableException e) {
            e.printStackTrace();
        } catch (NullException e) {
            e.printStackTrace();
        }


    }

    private String getFileName(String needDate) {
        File fileLog = new File(Constants.FILE_PATH_INFO.get(Constants.FILE_PATH_DIR_LOG));
        if (!fileLog.exists()) {
            fileLog.mkdir();
        }
        File[] files = fileLog.listFiles();
        if (files == null || files.length == 0) {
            return null;
        }
        //对文件名进行排序
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    if (o1.getName().length() > 10 && o2.getName().length() > 10) {
                        Date date1 = format.parse(o1.getName().substring(0, 10));
                        Date date2 = format.parse(o2.getName().substring(0, 10));
                        if (date1.before(date2)) {
                            return -1;
                        } else {
                            return 1;
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                return 1;
            }
        });

        String fileName ="";
        if(TextUtils.isEmpty(needDate)){
            fileName = files[files.length-1].getName();
        }else{
            for (int i = 0; i < files.length; i++) {
                fileName = files[i].getName();
                if(fileName.startsWith(needDate)){
                    break;
                }
            }
        }
        return fileName;

    }

    /**
     *   下载成功，首先把状态置为0，然后 去安装，安装失败，把状态置为3
     * @param version
     * @param status
     * @param filePath
     * @param isFail  //安装失败，防止循环调用
     */

    public void updateStatus(String version,int status,String filePath,boolean isFail)  {
        TreeMap<String,String> data = new TreeMap<>();
        data.put("upgrade_status",status+"");
        data.put("dev_number",CommUtils.getDeviceSN());
        data.put("version",version);
        try {
            HttpBusiness.getInstance().post(context, Urls.UPDATE_STATUS, data, new ResultCallBack<LocalCommonBackJson>() {
                @Override
                public void onFail(int i, Exception e) {
                    isDownloadApk = true;
                }

                @Override
                public void onResponse(int i, LocalCommonBackJson localCommonBackJson) {
                    if(isFail){
                        isDownloadApk = true;
                       return;
                    }
                    if("0".equals(localCommonBackJson.getErr_code())){
                        int result =  ShellUtils.installApk(filePath);
                        if(result==0){
                            MyLog.d(MyLog.TAG,"安装成功");
                        }else{
                            updateStatus(version, 3,filePath,true);
                        }
                    }else{
                        isDownloadApk = true;
                    }

                }

                @Override
                public void onHttpFail(int i, String s) {
                    isDownloadApk = true;
                }
            });
        } catch (NetNotAvailableException e) {
            e.printStackTrace();
        } catch (NullException e) {
            e.printStackTrace();
        }


    }


/*
    public void test(){
        String result =  CommUtils.silentInstallApkByReflect("/sdcard/dcg.apk",context);
        MyLog.d(MyLog.TAG,"安装成功: result: " + result);
        if("success".equals(result)){
            rebootAndroid();
        }
    }
*/


}
